<template>
  <a-card title="新闻列表">
    <div class="table-page-search-wrapper">
      <a-table
        :dataSource="dataSource"
        :columns="columns"
        bordered
        :pagination="pagination"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'index'">
            {{ index + 1 }}
          </template>
          <template v-if="column.key === 'category'">
            {{ getEnumLabel(record.category, newsTypeList) }}
          </template>
          <template v-else-if="column.key === 'editorType'">
            {{ getEnumLabel(record.editorType, editTypeMaps) }}
          </template>
          <template v-else-if="column.key === 'updateTime'">
            {{ $dayjs(record.updateTime).format("YYYY-MM-DD HH:mm") }}
          </template>
          <template v-else-if="column.key === 'isPublish'">
            <a-tag :color="record.isPublish ? 'blue' : 'orange'">
              {{ column.options[record.isPublish] }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'isTop'">
            <a-tag :color="record.isTop ? 'blue' : 'orange'">
              {{ column.options[record.isTop] }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'cover'">
            <a-image v-if="record.cover" :src="record.cover" :width="88" />
          </template>
          <template v-else-if="column.key === 'action'">
            <a @click="handelPreview(record)">预览</a>
            <a-divider type="vertical" />
            <template v-if="!record.isPublish">
              <a @click="handelEdit(record)">编辑</a>
              <a-divider type="vertical" />
            </template>

            <a @click="handelPublish(record)">{{
              !record.isPublish ? "发布" : "取消发布"
            }}</a>
            <a-divider type="vertical" />
            <a @click="handelTop(record)">{{
              !record.isTop ? "置顶" : "取消置顶"
            }}</a>
            <template v-if="!record.isPublish">
              <a-divider type="vertical" />
              <a @click="handleDelete(record)" style="color: red">删除</a>
            </template>
          </template>
        </template>
      </a-table>
    </div>
  </a-card>
  <a-modal
    v-model:open="open"
    title="编辑"
    @ok="handleOk"
    width="60%"
    okText="更新"
    cancelText="取消"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :labelCol="{ span: 4 }"
      :wrapperCol="{ span: 20 }"
      :rules="rules"
    >
      <a-form-item label="标题" name="title">
        <a-input v-model:value="formState.title" />
      </a-form-item>
      <a-form-item label="类别" name="category">
        <a-radio-group v-model:value="formState.category" name="radioGroup">
          <a-radio
            :value="item.value"
            v-for="item in newsTypeList"
            :key="item._id"
            >{{ item.label }}
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="文本格式" name="editorType">
        <a-radio-group v-model:value="formState.editorType">
          <a-radio
            :value="item.value"
            v-for="item in editTypeMaps"
            :key="item.value"
          >
            {{ item.label }}
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="内容">
        <WangEditor
          v-model:value.lazy="formState.content"
          mode="defautl"
          v-if="!formState.editorType"
        >
        </WangEditor>
        <MackdownEditor
          v-model:value.lazy="formState.content"
          v-else
          :preview="false"
        />
      </a-form-item>
      <a-form-item label="封面">
        <Upload v-model:value.lazy="formState.cover"></Upload>
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal
    v-model:open="openPreView"
    @ok="openPreView = false"
    width="60%"
    :footer="null"
  >
    <Preview v-bind="previewValue"></Preview>
  </a-modal>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, reactive } from "vue";
import { getDictList } from "@/api/dict";
import MackdownEditor from "@/components/MackdownEditor";
import { editTypeMaps, getEnumLabel } from "@/utils/dict";
import Preview from "./preview.vue";
import { message } from "ant-design-vue";
import {
  getNewsList,
  publishNews,
  deleteNews,
  isTopNews,
  getNewsDetail,
  editNews,
} from "@/api/news";
const { appContext } = getCurrentInstance();
const { $dayjs } = appContext.config.globalProperties;

const open = ref(false);
const newsTypeList = ref([]);
const openPreView = ref(false);
const formRef = ref();
const formState = ref({});
const rules = reactive({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  editorType: [{ required: true, message: "请选择", trigger: "blur" }],
  type: [{ required: true, message: "请选择类型", trigger: "blur" }],
  cover: [{ required: true, message: "请上传封面", trigger: "blur" }],
  category: [{ required: true, message: "请选择分类", trigger: "blur" }],
});

const previewValue = ref("");
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  onChange: (current) => {
    pagination.value.current = current;
    getList();
  },
});
const columns = [
  {
    title: "序号",
    dataIndex: "index",
    key: "index",
  },
  {
    title: "标题",
    dataIndex: "title",
    key: "title",
  },
  {
    title: "类别",
    dataIndex: "category",
    key: "category",
  },
  {
    title: "类型",
    dataIndex: "editorType",
    key: "editorType",
  },
  {
    title: "作者",
    dataIndex: "author",
    key: "author",
  },
  {
    title: "封面",
    dataIndex: "cover",
    key: "cover",
  },
  {
    title: "修改日期",
    dataIndex: "updateTime",
    key: "updateTime",
  },
  {
    title: "是否发布",
    dataIndex: "isPublish",
    key: "isPublish",
    options: {
      0: "未发布",
      1: "已发布",
    },
  },
  {
    title: "是否置顶",
    dataIndex: "isTop",
    key: "isTop",
    options: {
      0: "默认",
      1: "置顶",
    },
  },
  {
    title: "操作",
    key: "action",
  },
];

const dataSource = ref([]);

const getList = async () => {
  const { msg, success, data } = await getNewsList({
    page: pagination.value.current,
    pageSize: pagination.value.pageSize,
  });
  if (success) {
    message.success(msg);
    dataSource.value = data.row || [];
    pagination.value.total = data.count;
  } else {
    message.error(msg);
  }
};

// 发布操作，取消发布
const handelPublish = async (row) => {
  const { _id, isPublish } = row;
  const { success, msg } = await publishNews({
    _id,
    isPublish: isPublish ? 0 : 1,
  });
  if (success) {
    message.success(msg);
    getList();
  } else {
    message.error(msg);
  }
};

// 发布操作，取消发布
const handelTop = async (row) => {
  const { _id, isTop } = row;

  const { success, msg } = await isTopNews({
    _id,
    isTop: isTop ? 0 : 1,
  });
  if (success) {
    message.success(msg);
    getList();
  } else {
    message.error(msg);
  }
};

// 删除操作
const handleDelete = async (row) => {
  const { _id } = row;
  const { msg, success } = await deleteNews({
    _id,
  });
  if (success) {
    message.success(msg);
    getList();
  } else {
    message.error(msg);
  }
};
// 编辑操作
const handelEdit = async (row) => {
  const { _id } = row;
  const { msg, success, data } = await getNewsDetail({
    _id,
  });
  if (success) {
    // message.success(msg);
    console.log({ data });
    formState.value = data;
    open.value = true;
  } else {
    message.error(msg);
  }
};
// 确定操作
const handleOk = async () => {
  formRef.value.validate().then(async () => {
    const { msg, success } = await editNews(formState.value);
    if (success) {
      message.success(msg);
      open.value = false;
      getList();
    } else {
      message.error(msg);
    }
  });
};
// 预览
const handelPreview = async (row) => {
  console.log(row);
  const { _id } = row;
  const { msg, success, data } = await getNewsDetail({
    _id,
  });
  if (success) {
    previewValue.value = {
      title: data.title,
      content: data.content,
      updateTime: $dayjs(data.updateTime).format("YYYY-MM-DD HH:mm:ss"),
    };
    openPreView.value = true;
  } else {
    message.error(msg);
  }
};
/**
 * 获取字典列表
 */
const getDictListFun = async (data) => {
  return await getDictList(data);
};

onMounted(async () => {
  getList();
  const newsTypeRes = await getDictListFun({
    name: "newsType",
  });
  if (newsTypeRes.success) {
    newsTypeList.value = newsTypeRes.data || [];
  } else {
    newsTypeList.value = [];
  }
});
</script>


<style lang="scss" scoped>
</style>